<?php
namespace app\user\model;
use app\user\model\Auth as auth;
use app\common\model\Base;
/**
*用户模型主要用于用户的权限判断和用户的识别;
*1.用户为会员用户，或者教练用户，或者老板用户，三者其中的一种或者可以三者都是。
*2.用户的权限判断以及发送给用户token或者是用户的唯一标识来判断用户当前是否为登录状态
*3.用户模块中需要做的内容就是验证用户的当前使用的使用的终端设备
*4.当前用户上次登录的地点
*用户注册
*用户注册分为三种类型
*1.使用手机号码注册选择使用策略模式进行开发这样可以保证最大的灵活性，并且手机号码注册和微信注册使用两种分离成两个单独的类型进行使用。
*/
class User extends Base{
    protected static  $autoRefreshCache=true; //增加，修改，删除，自动更新缓存
    protected static  $cacheTag='user'; //缓存的名称,
    protected static  $autoPushCreateTime = true; //自动添加时间
    protected static  $autoPushUpdateTime = true; //自动添加修改时间
    //thinkphp5.0必须设置完整的数据表名称
    protected $table = 'gym_user_info';

    /**
     * [parseHashValue 解析hashValue成为用户的uuid]
     * @param  [type] $hashValue [description]
     * @return [type]            [description]
     */
    public static function parseHashValue($hashValue){
        if(empty($hashValue)){
            abort(-30,'hashValue不能是空的！');
        }
        $where = ['hash_value'=>$hashValue];
        $result = self::where($where)->field(['uuid']);
        $response = self::infoOfCache($result);
        if(empty($response)){
            abort(-47,'hashValue无效');
        }
        return $response[0]['uuid'];
    }
    //修改用户信息
    public static function monity(){
        self::couSave(
          [
            ['uuid','require','用户的编号不能为空！'],
          ],
          function($input,$self){
              $dataObject = new $self();
              $allowFields = ['gender','password','phone_num','nick_name','name','email_address','head_figure','motto','position'];
              $where=['uuid'=>$input['uuid']];
              $dataObject = new self();
              return $dataObject->allowField($allowFields)->isUpdate(true)->save($input,$where);
          }
        );

    }



    /**
    *用户下线的操作
    */
    public function offline($uuid=null){
        $allowFields = ['hash_value'];
        if(empty($uuid)){
            throw new \Exception('用户标识不能为空！');
        }
        //用户退出登录
        $success = $this->allowField($allowFields)->save(['hash_value'=>''],['uuid'=>$uuid]);
        if(!$success){
            throw new \Exception('退出登录错误请重试！');
        }
        return true;
    }

    /**
     * [infoByType 通过类型的值判断内容]
     * @param  array  $info [description]
     * @return [type]       [description]
     */
    public static function infoByType($info = []){

        $role = auth::getRoleStock($info['role']);
        if(!$role){
            abort(-70,'类型值不正确！');
        }
        //进行手机号码的搜索
        if(array_key_exists('phone_num', $info)){
            if(!empty($info['phone_num'])){
              $where = ['usi.phone_num'=>$info['phone_num'],'agr.group_id'=>$role];
              switch($info['role']){
                  case 'fitness':
                      $result = self::where($where)->alias('usi')->field(['usi.*','sg.gym_id','gi.store_title','gi.unique_id'])->join('__AUTH_GROUP_RELATION__ agr','usi.uuid = agr.uid','INNER');
                      $result->join('__SIGN_GYM__ sg','usi.uuid = sg.fitness_instructor_id','INNER');
                      $result->join('__GYM_INFO__ gi','sg.gym_id = gi.unique_id','INNER')->group('usi.phone_num');
                      break;
                  default:
                   $result = self::where($where)->alias('usi')->join('__AUTH_GROUP_RELATION__ agr','usi.uuid = agr.uid','INNER');
              }
              return self::infoOfCache($result);
            }
            return [];
        }
        return [];
    }

    /**
    *@param $info 用户的信息
    *搜索用户的信息，可以用户三种形式进行搜索
    *第一种形式是进行手机号码的搜索
    *第二种形式是进行用户的id进搜索
    *第三种信息是使用用户的名称进行搜索
    *@return
    */
    public static function info($info=[]){
        if(array_key_exists('role',$info)){
            //使用带有type值方法进行搜索
            if(!empty($info['role'])){
                return self::infoByType($info);
            }

        }
        $response = null;
        //判断是否具有用户的uuid,在进行uuid查询的时候一定是进入了用户的详情页面
        if(array_key_exists('uuid',$info) && preg_match('/\w+/',$info['uuid'])){
          if(empty($info['uuid'])){abort(-0040,'用户的uuid不能为空！');}
          $where = ['uuid'=>$info['uuid']];
          $field = ['usi.name','usi.nick_name','usi.phone_num','usi.email_address','usi.gender','usi.create_time','usi.status','usi.position','head_figure','usi.uuid','agr.group_id'];
          $response = collection(self::where($where)->alias('usi')->field($field)->join('__AUTH_GROUP_RELATION__ agr','usi.uuid = agr.uid','INNER')->select())->toArray();
          if(!empty($response)){
            $groups = array_column($response,'group_id'); //取出其中的角色内容
            $response = $response[0]; $response['group_id'] = $groups;
          }else{
            $response = null;
          }
        }
        //判断是否具有用户的phone_num电话号码
        if(array_key_exists('phone_num',$info) && preg_match('/^[13|18|17][0-9]+/',$info['phone_num'])){
            $where = ['phone_num'=>addslashes($info['phone_num'])];
            $field = ['name','uuid','nick_name','head_figure'];
            $response = collection(self::where($where)->field($field)->select())->toArray();
        }
        //判断用户的名称是否存在
        if(array_key_exists('name',$info)){
            //在用于列表搜索的情况下可以搜索到很多的内容
            $field = ['name','uuid','nick_name','head_figure'];
            $response = collection(self::where('name','like','%'.$info['name'].'%')->field($field)->select())->toArray();

        }
        //最后的一种情况是前面的都不匹配
        if(is_null($response)){
          $keyuuid = key($info);
          if(!empty($info) && preg_match('/\w+/',$keyuuid)){
            $where = ['uuid'=>$keyuuid];
            $field = ['usi.name','usi.nick_name','usi.phone_num','usi.email_address','usi.gender','usi.create_time','usi.status','head_figure','usi.uuid','agr.group_id'];
            $response = collection(self::where($where)->field($field)->alias('usi')->join('__AUTH_GROUP_RELATION__ agr','usi.uuid = agr.uid','RIGHT')->select())->toArray();
            if(!empty($response)){
              $groups = array_column($response,'group_id'); //取出其中的角色内容
              $response = $response[0]; $response['group_id'] = $groups;
            }else{
              $response = null;
            }
          }else{
              abort(-0001,'参数不正确！');
          }
        }
          //如果用户的名称不存在的时候使用默认的选项用户的uuid
          return is_null($response)? abort(-0010,'您查询的用户不存在！'):$response;

    }

    /**
     * [signIn 用户登录的接口]
     * @return [type] [description]
     */
    public static function signIn(){
        $data = self::getInputData();
        $type = $data['type'];
        $response = '';
        switch($type){
            //执行手机登录的操作
            case 'phone':
              $sign ='\\app\\user\\model\\login\\PhoneLogin';
              $sign::setInputData($data);
              $response = $sign::signIn();
              break;
            //执行微信登录的操作,威信小程序的登录
            case 'wechat_app':
              $sign = '\\app\\user\\model\\regist\\WechatRegist';
              $sign::setInputData($data);
              $response = $sign::signIn();
        }
        return $response;
    }

    /**
     * [getUserManagerUser 获取用户的主页信息数据包括用户的基本信息和用户的角色信息]
     * @return [type] [description]
     */
    public static function getUserManagerInfo($uuid){
          $response['role']= auth::getRoleInfo($uuid);
          $response['user_info']=[];
          $where = ['uuid'=>$uuid];
          $field = ['head_figure','nick_name','status','gender','email_address'];
          $result = self::where($where)->field($field);
          $userInfo = self::infoOfCache($result)[0];
          $response['user_info']= array_merge($response['user_info'],$userInfo);
          return $response;
    }

    /**
     * [managerInfo 登录后的主面板的信息]
     * 用户的主面板信息
     * @return [array] [返回需要的主面板信息]
     */
    public static function managerInfo($info){
        $uuid = array_key_exists('uid',$info)?$info['uid']:$info['uuid'];
        $role = array_key_exists('role',$info)?$info['role']:auth::getRoleInfo($uuid);
        $manager = '';
        switch($role){
            //会员的主页面板
            case 'member':
              $manager = '\\app\\user\\model\\MemberManager';
            break;
            //教练的主页面板
            case 'fitness':
              $manager = '\\app\\user\\model\\FitnessManager';
            break;
            //老板的主页面板
            case 'boss':
              $manager = '\\app\\user\\model\\BossManager';
            break;
            default:
              abort(-0045,'用户的角色不正确！');
        }
        $managerInfo  = $manager::getManagerInfo($uuid);
        $managerInfo['role'] = $role;
        return $managerInfo;
    }


    /**
     * [HashValue 创建用户的登录签名]
     */
    public static function HashValue($uuid){
        $createHashValue = '\\app\\user\\model\\login\\PhoneLogin';
        $hashValue = $createHashValue::generateUniqueSignForUser($uuid);
        $data['hash_value'] = $hashValue;
        $dataObject = new self();
        $result = $dataObject->save($data,['uuid'=>$uuid]);
        if(!$result){
            abort(-47,'系统错误请稍后重试！');
        }
        return $hashValue;
    }


    /**
     * [newUser 新增一个用户]
     * @return [type] [新增一个用户的内容]
     */
    public static function newUser(){
        $publicTool = '\\app\\publictool\\controller\\PublicTool';
        $allowField = true;
        $data['uuid'] = $publicTool::createUniqueId(); //生成用户的唯一标识符
        if(!array_key_exists('phone_num',$data)){
            $data['phone_num'] = 0;
        }
        if(!array_key_exists('email_address',$data)){
            $data['email_address'] = 'default';
        }

        if(!array_key_exists('password',$data)){
            $data['password'] = $publicTool::passwordEncryption('123456789');
        }

        if(!array_key_exists('gender',$data)){
            $data['gender'] = 0;
        }

        if(!array_key_exists('head_figure',$data)){
            $data['head_figure'] = $data;
        }
        $data['create_time'] = time();
        $data['last_login_time'] = time();
        $dataObject = new self();
        $result = $dataObject->data($data)->allowField($allowField)->save();
        if(!$result){
            abort(-45,'注册失败！');
        }
        return ['hash_value'=>self::hashValue($data['uuid']),'uuid'=>$data['uuid']];
    }

}
